package fr.vvins.core.jobs.catalog;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

import fr.vvins.core.catalog.entity.Vigneron;
import fr.vvins.core.catalog.entity.Vin;
import fr.vvins.core.catalog.entity.dao.VigneronRepository;
import fr.vvins.core.catalog.entity.dao.VinRepository;
import fr.vvins.core.dao.DataException;
import fr.vvins.core.jobs.JobException;
import fr.vvins.core.user.dao.FavoriteRepository;
import fr.vvins.core.user.dao.UserLogRepository;
import fr.vvins.core.user.entity.Favorite;
import fr.vvins.core.user.entity.UserLog;

public class CatalogJobs {

	private final static Logger log = LoggerFactory.getLogger(CatalogJobs.class);

	private VinRepository vinDao;
	private FavoriteRepository favoriteDao;
	private UserLogRepository userLogDao;
	private VigneronRepository vigneronDao;

	@Async
	public void updateScore() throws JobException {
		if (log.isDebugEnabled()) {
			log.debug("Catalog jobs start");
		}
		try {
			Iterable<Vin> vins = vinDao.findAll();
			for (Vin v : vins) {
				long f = 0;
				long l = 0;		
				//long f = favoriteDao.count("product.id=?", v.getId());
				//long l = userLogDao.count("product.id=?", v.getId());
				v.setFavorite(f);
				v.setLog(l);
				v.setSell(new Long(0));
				vinDao.save(v);
			}
			Iterable<Vigneron> vignerons = vigneronDao.findAll();
			for (Vigneron v : vignerons) {
				long f = 0;
				long l = 0;		
				//long f = favoriteDao.count("vigneron.id=?", v.getId());
				//long l = userLogDao.count("vigneron.id=?", v.getId());
				v.setFavorite(f);
				v.setLog(l);
				v.setSell(new Long(0));
				vigneronDao.save(v);
			}
		} catch (Throwable e) {
			throw new JobException(e.getMessage(), e);
		}

		if (log.isDebugEnabled()) {
			log.debug("Catalog jobs end");
		}
	}

	@Async
	public void updateVinScore(Integer id) throws JobException {
		if (log.isDebugEnabled()) {
			log.debug("Catalog jobs start");
		}
		try {
			Vin v = vinDao.findOne(id);
			long f = 0;
			long l = 0;		
			//long f = favoriteDao.count("product.id=?", id);
			//long l = userLogDao.count("product.id=?", id);
			v.setFavorite(f);
			v.setLog(l);
			v.setSell(new Long(0));
			vinDao.save(v);
		} catch (Throwable e) {
			throw new JobException(e.getMessage(), e);
		}
		if (log.isDebugEnabled()) {
			log.debug("Catalog jobs end");
		}
	}

	@Async
	public void updateVigneronScore(Integer id) throws JobException {
		if (log.isDebugEnabled()) {
			log.debug("Catalog jobs start");
		}
		try {
			Vigneron v = vigneronDao.findOne(id);
			long f = 0;
			long l = 0;		
			//long f = favoriteDao.count("vigneron.id=?", id);
			//long l = userLogDao.count("vigneron.id=?", id);
			v.setFavorite(f);
			v.setLog(l);
			v.setSell(new Long(0));
			vigneronDao.save(v);
		} catch (Throwable e) {
			throw new JobException(e.getMessage(), e);
		}

		if (log.isDebugEnabled()) {
			log.debug("Catalog jobs end");
		}
	}

}
